package Controllers;

import Information.PostInfo;
import Information.UserInfo;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

import static Application.ReadFileToString.readFile;

public class DraftsEditController extends Application implements Initializable {
    @FXML
    private ChoiceBox  tag;
    @FXML
    private TextField newPostTitle;   //标题文本
    @FXML
    private TextArea newPost;//正文文本
    private static String newPosts ;  //帖子
    private static String newPostTitles; //标题
    private static  String tags;//标签
    private UserInfo userInfo = new UserInfo();//用户信息,用来在controller之间传递用户信息
    private  PostInfo draftsInfo; //创建草稿对象
    private  String picturePath = null;


    //发布帖子
    public void post(ActionEvent event) throws Exception{//在fxml里配置onAction="#post"


            newPosts = newPost.getText();  //正文
            newPostTitles = newPostTitle.getText();
            tags=(String)tag.getValue();
        String newPostPath = null;   //帖子路径
        newPostPath =  "src/UserPosts/postTexts"; // 定位到用户帖子文件夹位置
        File f = new File(newPostPath) ;
        int size = f.listFiles().length + 1;   //确定为该用户第几个帖子
        newPostPath = newPostPath + "/" + size + ".txt";  //该帖子的完整路径
        String newTitlePath = "src/UserPosts/postTitles/"+ size + ".txt";
        if(!newPosts.isEmpty() && !newPostTitles.isEmpty())  //标题和内容不能为空
        {
        saveAsFileWriter(newPosts,newPostPath);   //将帖子发布并保存用户发布信息
        saveAsFileWriter(newPostTitles,newTitlePath);
        }
        String objectsPath = "src/UserPosts/postObjects/"+size+".ser";
        PostInfo postInfo = new PostInfo();  //创建帖子对象
        SimpleDateFormat time = new SimpleDateFormat("MM-dd HH:mm");//设置日期格式
        postInfo.setCreatedTime(time.format(new Date()));
        postInfo.setTextPath(newPostPath);
        postInfo.setPostId(""+size);
        postInfo.setTitlePath(newTitlePath);
        if(picturePath != null)
            postInfo.setImg(picturePath); //插入图片路径
        readUserInfo();
        postInfo.setAuthorId(userInfo.getId());
        postInfo.setTag(tags);  //加入标签
        String info="发布成功";
        if(!newPosts.isEmpty() && !newPostTitles.isEmpty())  //标题和内容不能为空
        try(
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(objectsPath)))
        {   //写入当前帖子对象
            oos.writeObject(postInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
    else
        info = "标题和内容不能为空,请写上内容再发布";
        Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
        alert.setHeaderText(null);
        alert.setTitle("提示");
        alert.show();

    }


    //保存草稿
    public void drafts(ActionEvent event) {//在fxml里配置onAction="#drafts"

        String draftsPath = null;   //草稿路径
        draftsPath =  "src/Drafts/draftsTexts"; // 定位到用户草稿文件夹位置
        String str = draftsInfo.getTextPath();
        str=str.trim();
        String size="";   //定位到该草稿
        if(str != null && !"".equals(str)){  //提取数字
            for(int i=0;i<str.length();i++){
                if(str.charAt(i)>=48 && str.charAt(i)<=57){
                    size+=str.charAt(i);
                }
            }
        }
        draftsPath = draftsPath + "/" + size + ".txt";  //该草稿的完整路径
        String draftsTitlePath = "src/Drafts/draftsTitles/"+ size + ".txt";
        saveAsFileWriter(newPost.getText(),draftsPath);   //将草稿发布并保存用户发布信息
        saveAsFileWriter(newPostTitle.getText(),draftsTitlePath);
        String objectsPath = "src/Drafts/draftsObjects/"+size+".ser";
        PostInfo postInfo = new PostInfo();
        postInfo.setTextPath(draftsPath);
        postInfo.setPostId(""+size);
        postInfo.setTitlePath(draftsTitlePath);
        if(picturePath != null)
            postInfo.setImg(picturePath);
        else postInfo.setImg(draftsInfo.getImg());
        readUserInfo();
        postInfo.setAuthorId(userInfo.getId());
        postInfo.setTag((String)tag.getValue());  //加入标签
        try(
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(objectsPath)))
        {   //写入当前草稿对象
            oos.writeObject(postInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String info="保存成功";
        Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
        alert.setHeaderText(null);
        alert.setTitle("提示");
        alert.show();
    }


    //插入封面图片
    public  void insert_picture(){

        try{
            Stage stage = null;
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择封面图片");
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))
            );
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                    new FileChooser.ExtensionFilter("GIF", "*.gif"),
                    new FileChooser.ExtensionFilter("BMP", "*.bmp"),
                    new FileChooser.ExtensionFilter("PNG", "*.png")
            );
            File selectedFile =fileChooser.showOpenDialog(stage);
            picturePath = selectedFile.getPath();
            String info = "成功插入封面，请点击直接发布发布帖子";
            Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
            alert.setHeaderText(null);
            alert.setTitle("提示");
            alert.show();
        }
        catch(Exception k){
            String info = "请选择文件，若找不到图片，可尝试改变搜索的图片类";
            Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
            alert.setHeaderText(null);
            alert.setTitle("提示");
            alert.show();
        }

    }



    private static void saveAsFileWriter(String content,String filePath) {
        //content为写入的字符串，filepath为写入文件的路径，将字符串写入文件

        FileWriter fwriter = null;
        try {

            fwriter = new FileWriter(filePath);
            fwriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fwriter.flush();
                fwriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    public static void clearInfoForFile(String fileName) { //将文件清空
        File file =new File(fileName);
        try {
            if(!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter =new FileWriter(file);
            fileWriter.write("");
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readUserInfo(){   //读取用户对象信息
        try(
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/UserPosts/currentUser.ser"))) {
            try {//读取当前用户对象
                try {
                    userInfo = (UserInfo) ois.readObject();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        try {
            AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("../Resources/DraftsEdit.fxml"));
            Scene scene = new Scene(root, 1267.0, 850.0);
            //scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.getIcons().add(new Image("/Images/logoblue.png"));
            primaryStage.setTitle("创作界面");
            primaryStage.setScene(scene);
            primaryStage.setResizable(false);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tag.getItems().addAll("杂谈","学习","运动","影视","科技","游戏", "日常", "艺术");
        tag.getSelectionModel().selectFirst();
        File file = new File("src/UserPosts/currentDrafts.ser");
        if(file.exists() && file.length() > 0)
            try (
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/UserPosts/currentDrafts.ser"))
            ) {
                //得到对象
                draftsInfo = (PostInfo) ois.readObject();
                //初始化
                File titleFile = new File(draftsInfo.getTitlePath());
                if(titleFile.exists() && titleFile.length() > 0){
                    setPostText(draftsInfo.getTitlePath(),draftsInfo.getTextPath());

                    tag.setValue(draftsInfo.getTag());}
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }

    }

    //设置正文
    public void setPostText(String titlePath,String path) {
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder;
        File titleFile = new File(titlePath);
        if(titleFile.exists() && titleFile.length() > 0)
            try {
                //创建bufferedReader, 进行readLine
                bufferedReader = new BufferedReader(new FileReader(path));
                BufferedReader titleReader = new BufferedReader(new FileReader(titlePath));
                newPostTitle.setText(titleReader.readLine());
                //用于拼接的字符串
                stringBuilder = new StringBuilder();
                //一行
                String line;

                //循环读取一行, 读完后把该行插入字符串, 并加上换行符
                while ( (line = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(line);
                    stringBuilder.append(System.getProperty("line.separator"));
                }

                //得到结果
                newPost.setText(stringBuilder.toString());

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //关闭流
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    }


}
